/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Interfaces;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import lemar.ConexionHibernate;
import lemar.entidad.Estante;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
/**
 *
 * @author Gu5Riv
 */
public class ConsultarEstante extends javax.swing.JPanel {

    //Atributos para el uso de Hibernate
    private static SessionFactory sessionFactory = null;
    
    public ConsultarEstante() {
        initComponents();
        
        //Se carga el comboBox Dinamicamente de la BD
        cargarComboBox();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        btnConsultarEstante = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtNumeroNiveles = new javax.swing.JTextField();
        cmbCodEstante = new javax.swing.JComboBox();
        txtUbicaBodega = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();

        setBackground(new java.awt.Color(255, 255, 255));
        setMaximumSize(new java.awt.Dimension(740, 430));
        setMinimumSize(new java.awt.Dimension(740, 430));
        setPreferredSize(new java.awt.Dimension(740, 430));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setText("Consultar un Estante");

        btnConsultarEstante.setText("Consultar");
        btnConsultarEstante.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConsultarEstanteActionPerformed(evt);
            }
        });

        jLabel5.setText("Número de Niveles");

        jLabel4.setText("Ubicación en Bodega");

        jLabel3.setText("Código del Estante");

        txtNumeroNiveles.setEditable(false);

        cmbCodEstante.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        txtUbicaBodega.setEditable(false);
        txtUbicaBodega.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtUbicaBodegaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(193, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel5)
                                    .addComponent(jLabel4))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtUbicaBodega, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtNumeroNiveles, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(18, 18, 18)
                                .addComponent(cmbCodEstante, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(196, 196, 196))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(287, 287, 287))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnConsultarEstante)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 391, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(156, 156, 156))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(59, 59, 59)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(52, 52, 52)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel3)
                            .addComponent(cmbCodEstante, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(txtUbicaBodega, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addComponent(txtNumeroNiveles, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 139, Short.MAX_VALUE)
                .addComponent(btnConsultarEstante)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void txtUbicaBodegaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtUbicaBodegaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtUbicaBodegaActionPerformed

    private void btnConsultarEstanteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultarEstanteActionPerformed
        
        
        String codigoEstante = "";
        
        List<Estante> estante = null;
        
        //Se extrae el nombre del proveedor seleccionado
        codigoEstante = cmbCodEstante.getSelectedItem().toString();
        
        if(codigoEstante.equalsIgnoreCase("<--Seleccione un estante-->")){
            JOptionPane.showMessageDialog(null,"Seleccione un código de estante","Selección de datos",JOptionPane.ERROR_MESSAGE);
        }
        else{
            
            //Chunche de Hibernate (Inicio de sesion de hibernate)
            Session session = null;
            //Cadena de seleccion de HQL
            String hql = "FROM lemar.entidad.Estante AS p WHERE p.codigoEstante = :codigoEstante";
            try{
                try{
                    //Conexion a la BD
                    sessionFactory = ConexionHibernate.getSessionFactory();
                    //Apertura de la sesion
                    session = sessionFactory.openSession();
                    Transaction txt = session.beginTransaction();                                       
                    
                    //Extraccion de los datos del estante de la BD                    
                    Query query = session.createQuery(hql).setString("codigoEstante", codigoEstante);
                    
                    //Se extrae los registros del estante
                    estante = query.list();
                    
                    //Se ponen los datos del estante en los campos de texto
                    //para su respectiva consulta
                   txtUbicaBodega.setText(estante.get(0).getUbicacion());
                   //Convertir de entero a String
                   int nNiv = estante.get(0).getNumeroNiveles();
                   String nNivString = Integer.toString(nNiv);
                   txtNumeroNiveles.setText(nNivString);
                   
                 
                                      
                    txt.commit();
                    
                     
                    }catch(Exception e){
                    System.out.println(e.getMessage());
                }
            } finally {
                //Finalizacion de la sesion de hibernate
                session.close();
                }
        } 
        
    }       
    
    //Metodo para cargar el comboBox dinamicamente de la BD
    private void cargarComboBox(){
        
        //Obtencion de todos los proveedores de la base de datos
        //para llenar el comboBox de manera dinamica
        
        //Variable que contendra la lista de proveedores
        List<Estante> listaProveedor = null;
        
        //Inicializacion de session de hibernate
        Session session = null;
        try{
            try{
                //Chunces que ocupa Hibernate
                sessionFactory = ConexionHibernate.getSessionFactory();
                session = sessionFactory.openSession();
                Transaction tx = session.beginTransaction();
                
                //Obteniendo de la BD todos los proveedores                
                listaProveedor = session.createQuery("from Estante").list();
                
                //Creando un modelo de comboBox                
                DefaultComboBoxModel modeloCombo = new DefaultComboBoxModel();
                
                //Poniendole un mensaje de seleccion (Pirmer elemento)
                 modeloCombo.addElement("<--Seleccione un estante-->");
                
                //Llenando el modelo de comboBox con los nombres de los proveedores
                for(Estante p : listaProveedor) 
                { 
                    modeloCombo.addElement(p.getCodigoEstante());                    
                }
                
                //Agregando el modelo del comboBox al comboBox del panel
                
                cmbCodEstante.setModel(modeloCombo);
                             
            }catch(Exception e){
                    System.out.println(e.getMessage());
                }
            }finally {
                session.close();
            }
 
    }//GEN-LAST:event_btnConsultarEstanteActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConsultarEstante;
    private javax.swing.JComboBox cmbCodEstante;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField txtNumeroNiveles;
    private javax.swing.JTextField txtUbicaBodega;
    // End of variables declaration//GEN-END:variables
}